package cn.wolfcode.resolver;


import cn.wolfcode.wolf2w.annotation.UserParam;
import cn.wolfcode.wolf2w.cache.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.domain.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/*
* 用于解析请求映射方法中声明的当前登录用户的对象信息
*
* */
public class UserInofArgumentResolver implements HandlerMethodArgumentResolver{
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    /**
     *
     * 表示当前解析器能解析哪种类型参数
     * 返回值是布尔类型，返回值为TRUE时表示支持解析指定类型
     * 返回值为false时表示不支持指定类型
     *
     * @param methodParameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType()== UserInfo.class&&methodParameter.hasParameterAnnotation(UserParam.class);
    }

    /**
     *  执行解析逻辑并注入参数
     *  前提：必须是supportsParameter方法返回true时才执行
     *
     * @param methodParameter
     * @param modelAndViewContainer
     * @param nativeWebRequest
     * @param webDataBinderFactory
     * @return
     * @throws Exception
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest req=nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        //返回值就是请求映射方法声明的形式参数的UserInfo对象的值
        String token = req.getHeader("token");
        UserInfo user = userInfoRedisService.getUserByToken(token);
        //即返回当前登录对象
        return user;
    }
}
